package com.topisv.tms.web.lead;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.apache.shiro.SecurityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.topisv.tms.entity.CustomerLead;
import com.topisv.tms.entity.Customers;
import com.topisv.tms.entity.EdiOrder;
import com.topisv.tms.entity.OrdenoSource;
import com.topisv.tms.service.CustomerLeadService;
import com.topisv.tms.service.CustomersService;
import com.topisv.tms.service.account.ShiroDbRealm.ShiroUser;
import com.topisv.tms.service.edi.lead.LeadService;
import com.topisv.tms.utils.lead.LeadUtil;

@Controller
@RequestMapping(value = "/leadMasterplate")
public class LeadMasterolateController {
	
	private static final Logger log = LoggerFactory.getLogger(LeadMasterolateController.class);

	private final static String init = "lead/leadInit";

	private final static String values = "lead/leadEdiOrderValues";
	@Autowired
	private LeadService leadService;
	@Autowired
	private CustomersService customersService;
	@Autowired
	private CustomerLeadService customerLeadService;

	@RequestMapping(value = "init")
	public String toSynWeightPage(Model model) {
		ShiroUser user = getShiroUser();
		List<Customers> customers=customersService.loadCustomerByAuthority(user);
		List<OrdenoSource> sources=customersService.findOrdenoSource(customers.get(0).getCustomerCode());
		model.addAttribute("sources", sources);
		model.addAttribute("customers", customers);
		return init;
	}

	
	public boolean isBlank(String val){
		return null == val || val.trim().length()==0;
	}
	
	@SuppressWarnings("unchecked")
	@RequestMapping(value = "lead/{customerCode}/{areaGroupCode}/{type}")
	public String syn(@PathVariable(value = "customerCode") String customerCode,@PathVariable(value = "areaGroupCode") String areaGroupCode,@PathVariable(value = "type") String type, Model model,
			ServletRequest request, RedirectAttributes redirectAttributes) {
		HttpServletRequest httpRequest = null;
		DiskFileItemFactory factory = null;
		ServletFileUpload upload = null;
		List<FileItem> items = null;
		Workbook rwb = null;
		try {
			log.info("订单导入开始");
			CustomerLead customerLead=this.customerLeadService.findByCustomerCodeAndOrdenoSource(customerCode, type);
			if(null != customerLead && !isBlank( customerLead.getParams())){
				
				
				httpRequest = (HttpServletRequest) request;
				httpRequest.setCharacterEncoding("UTF-8");
				factory = new DiskFileItemFactory();
				upload = new ServletFileUpload(factory);
				model.addAttribute("status", "1");
				
				items = upload.parseRequest(httpRequest);
				Iterator<FileItem> itr = items.iterator();
				int uploadFileCount=0;
				while (itr.hasNext()) {
					
					FileItem item = (FileItem) itr.next();
					if (!item.isFormField()) {// 非表单字段就是上传处理文件
						
						if (item.getName() != null && !item.getName().equals("")) {
							uploadFileCount++;
							List<EdiOrder> ediOrders = new ArrayList<EdiOrder>();
							// 获取Excel文件对象
							InputStream stream = item.getInputStream();
	
							if (item.getName().endsWith(".xls")) {// 解析xls
								rwb = new HSSFWorkbook(stream);
								int count = rwb.getNumberOfSheets();
								
								for (int i = 0; i < count; i++) {
									Sheet sheet = rwb.getSheetAt(i);
									int rows=sheet.getLastRowNum();//.getRows();
									if(rows>0){
										ediOrders.addAll(LeadUtil.setEdiOrder(customerLead,sheet));
									}
								}
							} else if (item.getName().endsWith(".xlsx")) {// 解析xlsx
								rwb = new XSSFWorkbook(stream);
								int count = rwb.getNumberOfSheets();
								for (int i = 0; i < count; i++) {
									XSSFSheet sheet = (XSSFSheet) rwb.getSheetAt(i);
									int rows=sheet.getLastRowNum();//.getRows();
									if(rows>0){
										ediOrders.addAll(LeadUtil.setEdiOrder(customerLead,sheet));
									}
								}
							}
							if(ediOrders.size()>0){
								Map<String, EdiOrder> maps = LeadUtil.getEdiOrders(ediOrders);// 订单汇总
								List<EdiOrder> mergeOrder = leadService.mergeOrder(maps.values(),customerCode, type);
								for(EdiOrder ediOrder:mergeOrder){
									ediOrder.setAreaGroupCode(areaGroupCode);
								}
								log.info("总共导入订单数量:"+mergeOrder.size());
								Map<String, List<EdiOrder>> mapEdiOrders=null;
								try {
									mapEdiOrders=leadService.saveHS(mergeOrder, type, customerCode);
									model.addAttribute("normal", mapEdiOrders.get("normal"));
									model.addAttribute("exception", mapEdiOrders.get("exception"));
									model.addAttribute("suspect", mapEdiOrders.get("suspect"));
									model.addAttribute("repeat", mapEdiOrders.get("repeat"));
									model.addAttribute("message", "订单导入成功");
									model.addAttribute("number",mergeOrder.size());
									log.info("导入成功");
									
								} catch (Exception e) {
									model.addAttribute("normal", new ArrayList<EdiOrder>());
									model.addAttribute("exception", new ArrayList<EdiOrder>());
									model.addAttribute("suspect", new ArrayList<EdiOrder>());
									model.addAttribute("message", e.getMessage());
									model.addAttribute("number",0);
									log.error(customerCode+"订单导入失败:",e);
									
								}
								
								log.info("正常单数量:"+mapEdiOrders.get("normal").size());
								log.info("异常单数量:"+mapEdiOrders.get("exception").size());
								log.info("疑似单数量:"+mapEdiOrders.get("suspect").size());
								log.info("重复单数量:"+mapEdiOrders.get("repeat").size());
							} else {
								uploadFileCount--; // 文件没有数据
							}
							
						} else {
							log.error(customerCode+"订单导入文件名为空");
						}
					}
					if(uploadFileCount <=0){
						model.addAttribute("message", "没有上传订单文件或订单文件无效或无数据");
						log.error(customerCode+"没有上传订单文件或订单文件无效或无数据");
					}
				} //  
			} else {
				model.addAttribute("message", "订单导入模板未设置或者格式无效");
				log.error(customerCode+"订单导入模板未设置或者格式无效");
			}
		} catch (Exception e) {
			model.addAttribute("message", "订单导入数据失败");
			log.error(customerCode+"订单导入失败",e);
		}
		return values;
	}

	/**
	 * 导出模板
	 */
	@SuppressWarnings("deprecation")
	@RequestMapping(value = "updownExcel")
	public void updownExcel(ServletRequest request,
			ServletResponse response) {

		HttpServletRequest httpRequest = (HttpServletRequest) request;
		HttpServletResponse httpResponse = (HttpServletResponse) response;

		try {

			// path是指欲下载的文件的路径。
			File file = new File(httpRequest.getRealPath("/")
					+ "/WEB-INF/file/" + "template_order.xls");
			// 取得文件名。
			String filename = file.getName();

			// 以流的形式下载文件。
			InputStream fis = new BufferedInputStream(new FileInputStream(file));
			byte[] buffer = new byte[fis.available()];
			fis.read(buffer);
			fis.close();

			// 清空response
			httpResponse.reset();
			// 设置response的Header
			httpResponse.addHeader(
					"Content-Disposition",
					new StringBuilder().append("attachment;filename=").append(filename).toString());
			httpResponse.addHeader("Content-Length", "" + file.length());
			OutputStream toClient = new BufferedOutputStream(
					httpResponse.getOutputStream());
			response.setContentType("application/octet-stream");
			toClient.write(buffer);
			toClient.flush();
			toClient.close();

		} catch (IOException ex) {
			
		}
	}

	/**
	 * 取出Shiro中的当前用户Id.
	 */
	private ShiroUser getShiroUser() {
		ShiroUser user = (ShiroUser) SecurityUtils.getSubject().getPrincipal();
		return user;
	}
}
